package com.live.video.util;

import com.live.video.conf.AppConfig;
import org.nutz.ssdb4j.SSDBs;
import org.nutz.ssdb4j.spi.SSDB;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * User: dai
 * Date: 2017/5/7
 * Time: 14:48
 * Description:我的SSDB连接池
 */
@Component
public class MySSDBPool {
    private static Logger logger = LoggerFactory.getLogger(MySSDBPool.class);

    @Autowired
    private AppConfig config;

//    private static MySSDBPool inst = null;

//    private Map<String, SSDB> ssdbmap;
//    public static MySSDBPool getInstance(){
//        if(inst == null){
//            inst = new MySSDBPool();
//        }
//        return inst;
//    }

//    public MySSDBPool(){
//        String host = config.getSsdbHost();
//        int port = config.getSsdbPort();
//        logger.info("getSSDBClient host = {} ,port = {}",host,port);
//        ssdbmap = new HashMap<String, SSDB>();
//    }

    // Try to get ssdb for host and port
    public SSDB borrowSSDB(String host, int port) {
        SSDB retVal = null;
        if (host == null || host.isEmpty() || port <= 0) {
            return retVal;
        }
//        String key = host + ":" + port;
//        synchronized(ssdbmap){
//            retVal = ssdbmap.get(key);
//            logger.info("ssdbmap.size() = {}",ssdbmap.size());
//            if(retVal == null){
        retVal = SSDBs.pool(host, port, 5000, null);
//                if(retVal != null){
//                    ssdbmap.put(key, retVal);
//                }
//            }
//        }
        return retVal;
    }

    public SSDB borrowSSDB() {
        String host = config.getSsdbHost();
        int port = config.getSsdbPort();
        logger.info("getSSDBClient host = {} ,port = {}", host, port);
        SSDB retVal = borrowSSDB(host, port);
        return retVal;
    }
}
